package objetos;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class Planilha {

	private List<Impostos> impostos = new ArrayList<Impostos>();
	private Salario salario = new Salario();

	public Planilha() throws BiffException, IOException {

		Workbook workbook;
		workbook = Workbook.getWorkbook(new File("aliquota_salario_CLT.xls"));// xsl com as cidades.

		Sheet sheet = workbook.getSheet(0);
		String valorDe = "";
		String valorPara = "";
		String aliquota = "";
		String deduzir = "";
		String inss = "";

		for (int lin = 1; lin < sheet.getRows(); lin++) {

			Impostos s = new Impostos();
			valorDe = sheet.getCell(0, lin).getContents();
			valorPara = sheet.getCell(1, lin).getContents();
			aliquota = sheet.getCell(2, lin).getContents();
			deduzir = sheet.getCell(3, lin).getContents();
			inss = sheet.getCell(4, lin).getContents();

			if (valorDe != null && !valorDe.isEmpty()) {
				s.setSalarioDe(Double.parseDouble(valorDe.replaceAll(",", ".")));
			}
			if (valorPara != null && !valorPara.isEmpty()) {
				s.setSalarioAte(Double.parseDouble(valorPara.replaceAll(",", ".")));
			}
			if (aliquota != null && !aliquota.isEmpty()) {
				if ("-".equals(aliquota)) {
					s.setAliquota(1);
				} else {
					s.setAliquota(Double.parseDouble(aliquota.replaceAll(",", ".")));
				}
			}
			if (deduzir != null && !deduzir.isEmpty()) {
				if ("-".equals(deduzir)) {
					s.setDeduzir(0);
				} else {
					s.setDeduzir(Double.parseDouble(deduzir.replaceAll(",", ".")));
				}
			}
			if (inss != null && !inss.isEmpty()) {
				s.setInss(Double.parseDouble(inss.replaceAll(",", ".")));
			}

			impostos.add(s);
		}

		sheet = workbook.getSheet(1);

		salario.setSalarioBruto(Double.parseDouble((sheet.getCell(1, 0).getContents()).replaceAll(",", ".")));
		salario.setPerINSS(Double.parseDouble((sheet.getCell(1, 1).getContents()).replaceAll(",", ".")));
		salario.setBeneficio(Double.parseDouble((sheet.getCell(1, 2).getContents()).replaceAll(",", ".")));
		salario.setPartLucros(Double.parseDouble((sheet.getCell(1, 3).getContents()).replaceAll(",", ".")));

		workbook.close();

	}

	public Impostos getImpostos() {
		for (Impostos s : impostos) {
			if (this.salario.getSalarioBruto() >= s.getSalarioDe() && this.salario.getSalarioBruto() <= s.getSalarioAte()) {
				return s;
			}
		}
		return null;
	}

	public Salario getSalario() {
		return salario;
	}

	public void setSalario(Salario salario) {
		this.salario = salario;
	}
}
